import datetime

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
from apps.web import models
from django.conf import settings


class Tracer(object):
    # 初始化
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddlWare(MiddlewareMixin):
    def process_request(self, request):
        """
        如果用户已登录，则在request中赋值
        函数有返回值，则不继续往下执行
        """
        # 实例化对象
        request.tracer = Tracer()

        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()

        request.tracer.user = user_obj

        # 白名单，没有登录也可访问的url
        """
        1.获取当前用户访问的url
        2.判断url是否在白名单中
        """
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        # 检查用户是否登录, 为登录则重定向到index
        if not request.tracer.user:
            return redirect('/index/')

        # 登录成功后获取用户拥有的额度
        # 在交易记录中查找当前用户id值最大（即最近的交易记录）
        _object = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 判断该交易是否过期
        current_time = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_time:
            # 过期
            _object = models.Transaction.objects.filter(user=user_obj, status=2, price_policy__category=1).first()
        # 存储当前用户的额度信息
        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, view, args, kwargs):
        # 判断url是否是manage开头
        if not request.path_info.startswith('/manage/'):
            return
        # 判断当前项目id是否是我创建的或我参与的
        # 拿到当前项目id
        project_id = kwargs.get('project_id')
        # 判断是否是我创建的
        my_project = models.Project.objects.filter(id=project_id, creator=request.tracer.user).first()
        # 是我创建的
        if my_project:
            request.tracer.project = my_project
            return
        # 若不是我创建的，则判断是否是我参与的
        join_project = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        # 是我参与的
        if join_project:
            request.tracer.project = join_project.project
            return
        # 不是我创建和参与的
        return redirect('project_list')